package com.huey.utils.time;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

public class DateUtil {
    public final static String DATE_FORMAT_PATTERN = "yyyy-MM-dd";
    public final static String LONG_DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static String getCurrDateStr() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT_PATTERN);
        String format = formatter.format(LocalDateTime.now());
        return "-" + format;
    }

    public static String date2String(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_PATTERN);
        return sdf.format(date);
    }

    public static String date2String(Date date, String formatter) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatter);
        return sdf.format(date);
    }

    public static Date plusDay(Date currDate, Integer day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(currDate);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }

    public static Date plusMonth(Date currDate, Integer month) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(currDate);
        cal.add(Calendar.DAY_OF_MONTH, month);
        return cal.getTime();
    }

    /**
     * localDate转Date
     */
    public static Date localDate2Date(LocalDate localDate) {
        if (null == localDate) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

    /**
     * Date 转 localDate
     */
    public static LocalDate date2LocalDate(Date date) {
        Instant instant = date.toInstant();
        ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
        return zdt.toLocalDate();
    }


    public static Date asDate(LocalDateTime localDateTime) {
        if (Objects.isNull(localDateTime)) {
            return null;
        }
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取上一月
     *
     * @param date 日期
     * @return
     */
    public static Date getLastMonth(Date date) {
        Calendar currentMonth = Calendar.getInstance();
        currentMonth.setTime(date);
        currentMonth.add(Calendar.MONTH, -1);
        return currentMonth.getTime();
    }

    /**
     * 获取上一年
     *
     * @param date 日期
     * @return
     */
    public static Date getLastYear(Date date) {
        Calendar currentMonth = Calendar.getInstance();
        currentMonth.setTime(date);
        currentMonth.add(Calendar.YEAR, -1);
        return currentMonth.getTime();
    }
}
